package ZookeeperTest;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.util.List;

public class ZookeeperDemo {
private static String connectString="bigdata211:2181,bigdata212:2181,bigdata213:2181";
private static int sessionTimeout=2000;//延迟时间毫秒
private static  Watcher watcher = (watchedEvent) -> {
    System.out.println(watchedEvent.getType()+"--"+watchedEvent.getPath());
     };//lambda表达式表达内名内部类
     private ZooKeeper ZKclient=null;
    @Before//在执行Test之前会执行Before
    public void init() throws IOException {//初始化

        ZKclient = new ZooKeeper(
                connectString,//连接地址的端口号
                sessionTimeout, //超时时间
                watcher//监听器
                /*new Watcher() {
                    @Override
                    public void process(WatchedEvent watchedEvent) {

                    }
                }*/
        );


    }
    //1.创建子节点
    @Test
    public void creatChildNode() throws KeeperException, InterruptedException {
        ZKclient.create("/IDEA",//要创建的节点路径
                  "test".getBytes(),//节点的数据
                  ZooDefs.Ids.OPEN_ACL_UNSAFE,//节点访问权限
                  CreateMode.PERSISTENT//节点类型
               );


    }
    //2.监控节点
    @Test
    public void watchChild() throws KeeperException, InterruptedException {
        List<String> children = ZKclient.getChildren("/IDEA", true);
        for (String child: children) {
            System.out.println(child);
        }
        //延时他堵塞
       Thread.sleep(Integer.MAX_VALUE);
    }
    //3.判断Znode是否存在
    @Test
    public  void isExist() throws KeeperException, InterruptedException {
        Stat stat = ZKclient.exists("/IDEA", false);
        System.out.println(stat==null?"not exist":"exit");
    }
}